package com.woniuxy.java102vuecli.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.java102vuecli.controller.ResponseResult;
import com.woniuxy.java102vuecli.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author author
 * @Create 2023-09-21 11:34
 */
@Slf4j
@Component
public class LoginInterceptor2 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginInterceptor");
        //对OPTIONS请求放行

        if(request.getMethod().equals("OPTIONS")){
            log.info("OPTIONS请求，放行");
            return true;
        }
        response.setContentType("text/html;charset=utf-8");
        String token = request.getHeader("token");
        String refresh = request.getHeader("refresh");
        if(!StringUtils.isEmpty(token)&& JwtUtil.validate(token)){
            log.info("token有效，验证是否过期");
            if(!JwtUtil.isExpire(token)){
                log.info("token有效，token没有过期，直接放行");
                return true;
            }else{
                log.info("token有效，token过期，验证refresh");
                if(!StringUtils.isEmpty(refresh)&& !JwtUtil.isExpire(refresh)){
                    log.info("token有效，token过期，验证refresh,refresh有效，refresh没有过期,重新生成双token，放行");
                    token = JwtUtil.createToken(JwtUtil.getEid(token), JwtUtil.getEname(token));
                    refresh = JwtUtil.createRereshToken(JwtUtil.getEid(token), JwtUtil.getEname(token));
                    response.setHeader("token", token);
                    response.setHeader("refresh", refresh);
                    return true;
                }else{
                    log.info("token有效，token过期，验证refresh,refresh过期,拦截");
                    ResponseResult<String> responseResult=new ResponseResult<>(401,"error","token有效，token过期，验证refresh,refresh过期,拦截");
                    response.getWriter().write(new ObjectMapper().writeValueAsString(responseResult));
                    return false;

                }
            }
        }else{
            log.info("token无效，拦截");
            ResponseResult<String> responseResult=new ResponseResult<>(401,"error","未登录");
            response.getWriter().write(new ObjectMapper().writeValueAsString(responseResult));
            return false;
        }

    }
}
